using System.Collections;
using System.Collections.Generic;
using UnityEngine;

enum ZombieState
{
    Move,
    Eat,
    Die
}

public class Zombie : MonoBehaviour
{
    private float speed = 0.3f;
    private Vector3 position;
    private int hp = 200;
    private Animator animator;
    private ZombieState curState;
    private Plant curContactPlant;
    private int atkValuem = 20;
    private float eatCycle = 0.5f;
    private float eatTimer;
    private Collider2D zombieCollider;


    private void Start()
    {
        TryGetComponent<Animator>(out animator);
        TryGetComponent<Collider2D>(out zombieCollider);
    }
    void Update()
    {

        switch (curState)
        {
            case ZombieState.Move:
                Move();
                break;
            case ZombieState.Eat:
                Eat();
                break;
            case ZombieState.Die:
                Die();
                break;
            default:
                break;
        }
        
    }
    private void Move()
    {
        position = transform.position;
        transform.position = new Vector3(position.x - Time.deltaTime * speed, position.y, position.z);
    }

    public void Hit(int damage)
    {
        this.hp -= damage;
        if (hp <= 0)
        {
            curState = ZombieState.Die;
        }
    }

    void Die()
    {
        zombieCollider.enabled = false;
        animator.SetFloat("HP", -1);
        //Destroy(gameObject); 
    }

    void Eat()
    {
        if (eatTimer >= eatCycle)
        {
            eatTimer = 0;
        }
        eatTimer += Time.deltaTime;
        if (eatTimer >= eatCycle)
        {
            curContactPlant.Hit(atkValuem);
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Plant")
        {
            animator.SetBool("IsAttacking", true);
            curState = ZombieState.Eat;
            collision.gameObject.TryGetComponent<Plant>(out curContactPlant);
        }
        
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.tag == "Plant")
        {
            animator.SetBool("IsAttacking", false);
            curState = ZombieState.Move;
            curContactPlant = null;
        }
    }

    
}
